package com.winexpress.session.account;

import com.winexpress.entity.Admin;
import com.winexpress.entity.User;
import com.winexpress.helper.AESEncryptor;
import com.winexpress.helper.Config;
import com.winexpress.helper.Encryptor;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
@LocalBean
public class AdminSessionBean {

    @PersistenceContext
    private EntityManager em;

    public String loginAdmin(User admin) throws Exception {
        String strQuery = "SELECT d FROM User d WHERE d.email = :inEmail AND d.password = :inPassword";
        Query query = em.createQuery(strQuery);
        query.setParameter("inEmail", AESEncryptor.encrypt(Config.seed, admin.getEmail()));
        query.setParameter("inPassword",admin.getPassword());
        List<User> list = (List<User>) query.getResultList();
        if (!list.isEmpty()) {
            User user = list.get(0);
            if (user.isAdminUser() && user.isActivated()) {
                return user.getId().toString();
            }
        }
        return null;
    }

    public Admin getAdminById(Long id) {
        return em.find(Admin.class, id);
    }

    public Admin updateAdminParticular(Admin admin) throws Exception {;
        em.merge(admin);
        em.flush();
        return admin;
    }

    public Long registerNewAdmin(Admin admin) throws Exception {
        em.persist(admin);
        return admin.getId();
    }
}
